<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>对象拷贝</h1>
<hr>

<script>

    //在Javascript中当我们给一个集合中添加对象时，通常只是添加了对象的引用，简单来说就是一个对象的副本，它只分配一个引用。
    /*
    let stu = {
        name: 'zhangsan',
        age :18
    }

    let stuList = [];

    stuList.push(stu);
    stuList.push(stu);
    stuList.push(stu);

    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);

    })
    //更改对象属性
    stu.name = "李四";
    stu.age = 20;
    stuList.push(stu);
    console.log("-----更改学生姓名后------");
    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
    })

    */


    //1.JSON.parse(JSON.stringify(object))实现拷贝

    /*
    let stu = {
        name: 'zhangsan',
        age :18
    }

    let stuList = [];

    stuList.push(JSON.parse(JSON.stringify(stu)));
    stuList.push(JSON.parse(JSON.stringify(stu)));
    stuList.push(JSON.parse(JSON.stringify(stu)));

    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);

    })

    stu.name = "李四";
    stu.age = 20;
    stuList.push(JSON.parse(JSON.stringify(stu)));
    console.log("-----更改学生姓名后------");
    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
    })

    */

    //但是使用这种方法的弊端就是如果这个对象中不仅仅是简单的数据，而是定义了方法的话，那么这样的对象拷贝时定义的方法是无法拷贝的。
    /*
    let stu = {
        name: 'zhangsan',
        age :18,
        study: function(){
            console.log(this.name + " is good good study!");
        }
    }

    let stuList = [];
    stuList.push(JSON.parse(JSON.stringify(stu)));
    stuList.push(JSON.parse(JSON.stringify(stu)));
    stuList.push(JSON.parse(JSON.stringify(stu)));

    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
        s.study();
    })

    stu.name = "李四";
    stu.age = 20;
    stuList.push(JSON.parse(JSON.stringify(stu)));
    console.log("-----更改学生姓名后------");
    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
        s.study();
    })
    */

    //2.Object.assign() 实现拷贝

    let stu = {
        name: 'zhangsan',
        age :18,
        study: function(){
            console.log(this.name + " is good good study!");
        }
    }

    let stuList = [];
    stuList.push(Object.assign({},stu));
    stuList.push(Object.assign({},stu));
    stuList.push(Object.assign({},stu));

    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
        s.study();
    })

    stu.name = "李四";
    stu.age = 20;
    stuList.push(Object.assign({},stu));
    console.log("-----更改学生姓名后------");
    stuList.forEach(function(s,i){
        console.log("姓名："+s.name+",年龄："+s.age);
        s.study();
    })
</script>
</body>
</html>